package com.beerbear.springbootsecurity.controller;

import com.beerbear.springbootsecurity.entity.User;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Beer Bear
 * @Description: 登录
 * @Date: 2021/9/13 9:27
 */
@RestController
public class LoginController {

    /**
     * create by: Beer Bear
     * description: 登录
     * create time: 2021/9/13 9:33
     */
    @PostMapping("/login")
    public String Login(@RequestBody User user){
        if(user.getPassword().equals("admin") && user.getUsername().equals("admin")){
            // 账号密码正确了才将认证信息放到上下文中（用户权限需要再从数据库中获取，后面再说，这里省略）
            Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return "登录成功！";
        }
        return "账号密码错误";
    }

    @GetMapping("api")
    public String api(){
        return "调用api成功！";
    }
}
